package com.zj.juc.study.threadLocal;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @author 自己的名字
 * @version 1.0.0
 * @ClassName ThreadLocalDemo
 * @Description ThreadLocal
 * @createTime 2025年01月04日 14:34
 */
public class ThreadLocalDemo {

    public static void main(String[] args) {
        SellHouse sellHouse = new SellHouse();

        for (int i = 0; i < 5; i++) {
            int anInt = new Random().nextInt(6)+1;
            new Thread(()->{
                try {
                    for (int j = 0; j < anInt; j++) {
                        sellHouse.sellByThreadLocal();
                    }
                    System.out.println(Thread.currentThread().getName()+"sell count"+sellHouse.threadLocal.get());
                } finally {
                    sellHouse.threadLocal.remove();
                }
            },String.valueOf(i)).start();
        }

    }
}


class SellHouse{
    public int count = 0;

    public synchronized void sell(){
        count++;
    }

    ThreadLocal<Integer> threadLocal = ThreadLocal.withInitial(()->0);

    public void sellByThreadLocal(){
        threadLocal.set(1+threadLocal.get());
    }
}